package com.hgq.jssjyyxt.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hgq.jssjyyxt.constant.RedisConstant;
import lombok.extern.slf4j.Slf4j;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义的拦截器类 - 实现 HandlerInterceptor 接口
 */
@Component
@Slf4j
public class CustomInterceptor implements HandlerInterceptor {

    @Resource
    RedisTemplate<String, Integer> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在这里编写拦截逻辑，类似过滤器
        if (shouldBypass(request)) {
            return true;
        } else {
            //前段请求标识
            if (RedisConstant.CARD.equals( request.getHeader(RedisConstant.CARD))){
                return true;
            }
            if (isValidToken(request)) {
                return true;
            } else {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("Token失效，请重新登录");
                return false;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        log.info("请求拦截器 - 在请求处理之后调用，但在视图被渲染之前");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        log.info("请求拦截器 - 在请求处理完成后调用");
    }

    // 自定义放行逻辑，例如针对某些接口放行
    private boolean shouldBypass(HttpServletRequest request) {
        //放行登录接口和注册接口
        String uri = request.getRequestURI();
        return uri.contains("/trainers/login") ||
                uri.contains("/trainers/register") ||
                uri.contains("/upload/img") ||
                uri.contains("/images/") ||
                uri.contains("/error");
    }

    // 自定义 Token 验证逻辑
    private boolean isValidToken(HttpServletRequest request) {
        //获取请求头中的token
        String adminToken = request.getHeader(RedisConstant.ADMIN_TOKEN);
        String userToken = request.getHeader(RedisConstant.USER_TOKEN);

        log.info("adminToken:{},userToken:{}", adminToken, userToken);
        //判断token是否为空
        if (!StringUtils.hasLength(adminToken) && !StringUtils.hasLength(userToken)) {
            return false;
        }

        return this.validToken(adminToken, userToken);
    }

    private boolean validToken(String adminToken, String userToken) {
        boolean isAdminTokenPass = false;
        boolean isUserTokenPass = false;
        if (StringUtils.hasLength(adminToken)) {
            Integer id = redisTemplate.opsForValue().get(adminToken);
            isAdminTokenPass = null != id && id != 0;
        }

        if (StringUtils.hasLength(userToken)) {
            Integer id = redisTemplate.opsForValue().get(userToken);
            isUserTokenPass = null != id && id != 0;
        }
        return isAdminTokenPass || isUserTokenPass;
    }
}
